package com.android.example.record.utils;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.android.example.record.R;
import com.android.example.record.activity.DetailsActivity;
import com.android.example.record.bean.HistoryData;
import com.android.example.record.databinding.PopupBinding;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PopupDataUtil {

    static Toast toast;

    /**
     * 点击item，显示弹窗
     *
     * @param position        item的文字
     * @param activity        上下文为活动，okhttp3.Callback实例化需要的参数
     * @param historyDataList HistoryData列表
     */
    public static void showPopupWindow(int position, AppCompatActivity activity, List<HistoryData> historyDataList) {
        PopupBinding binding = PopupBinding.inflate(LayoutInflater.from(activity), null, false);
        View contentView = binding.getRoot();
        Callback callback = testCallback(position, activity);
        final PopupWindow popupWindow = getPopupWindow(contentView);
        popupWindow.setAnimationStyle(R.style.PopupWindow_anim_style);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor((v, event) -> {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_UP) {
                v.performClick();
            }
            return false;
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        // popupWindow.setFocusable(true);
        // popupWindow.update();
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);

        binding.uploadItem.setOnClickListener(v -> uploadItem(activity, callback));

        binding.details.setOnClickListener(v -> {
            HistoryData historyData = historyDataList.get(position);
            Intent intent = new Intent(activity, DetailsActivity.class);
            intent.putExtra("ID", historyData.getId());
            activity.startActivity(intent);
            popupWindow.dismiss();
        });

        binding.cancel.setOnClickListener(v -> popupWindow.dismiss());

        setWindowAlpha(0.23f, activity);
        popupWindow.setOnDismissListener(() -> setWindowAlpha(1f, activity));
    }

    public static PopupWindow getPopupWindow(View contentView) {
        return new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
    }

    private static void uploadItem(AppCompatActivity activity, Callback callback) {
        Utils.displayToast(activity, "连接服务", toast);
        String uri = Utils.getUploadPictureUri(activity);
        OkHttpUtils.doGetRequest(uri, callback);
    }

    // 初始化上传文件的数据
    private static String getJSON(int position, AppCompatActivity activity) {
        List<HistoryData> historyDataPicList = LitePal.findAll(HistoryData.class);
        HistoryData historyData = historyDataPicList.get(position);
        String jsonData = historyData.jsonString(activity);
        Log.d("data", jsonData);

        return jsonData;
    }

    private static void setWindowAlpha(float alpha, AppCompatActivity activity) {
        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
        params.alpha = alpha;
        activity.getWindow().setAttributes(params);
    }

    public static Callback getCallback(AppCompatActivity activity) {

        return new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                if (response.isSuccessful()) {
                    new Thread(() -> {
                        try {
                            String responseString = response.body().string();
                            activity.runOnUiThread(() -> {
                                if (responseString.contains("Index of /Picture")) {
                                    Utils.displayToast(activity, "上传成功", toast);
                                    Log.d("onResponse", responseString);
                                    return;
                                } else {
                                    Utils.displayToast(activity, "上传失败\n" + responseString, toast);
                                }

                                // if (responseString.contains("0x0000") && responseString.contains("成功")) {
                                //     Utils.displayToast(activity, "上传成功", toast);
                                //     Log.d("onResponse", responseString);
                                // } else {
                                //     Utils.displayToast(activity, "上传失败\n" + responseString, toast);
                                // }
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
            }
        };
    }

    public static Callback testCallback(int position, AppCompatActivity activity) {
        return new Callback() {

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response testResponse) {
                activity.runOnUiThread(() -> Utils.displayToast(activity, "连接成功", toast));
                OkHttpUtils.doPostRequest(
                        Utils.getUploadPictureUri(activity), getJSON(position, activity), getCallback(activity));
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                activity.runOnUiThread(() -> Utils.displayToast(activity, "连接失败\n" + e.getMessage(), toast));
            }
        };
    }

    public static Callback testCallback(String jsonString, AppCompatActivity activity) {
        return new Callback() {

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response testResponse) {
                activity.runOnUiThread(() -> Utils.displayToast(activity, "连接成功", toast));
                OkHttpUtils.doPostRequest(Utils.getUploadPictureUri(activity), jsonString, getCallback(activity));
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                activity.runOnUiThread(() -> Utils.displayToast(activity, "连接失败\n" + e.getMessage(), toast));
            }
        };
    }
}
